"""
Case Type   : borrow_memory
Case Name   : max_borrow_memory边界值校验
Create At   : 2025/4/14
Owner       : @li-xin12345
Description :
    1、设置max_borrow_memory=2147483647KB、2048GB、2147483648KB、
    -128MB、2049GB、128KB
    2、清理环境
Expect      :
    1、合理报错
    2、成功
History     :
"""

import os
import unittest

from testcase.utils.CommonSH import CommonSH
from testcase.utils.Common import Common
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class BorrowMemoryTest(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_db_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.common = Common()
        self.param_name = 'max_borrow_memory'
        self.default_value = self.common.show_param(self.param_name)
        self.invalid_values = ['2147483647kB', '2048GB', '2147483648kB',
                               '-128MB', '2049GB', '128kB']

    def test_borrow_memory(self):
        text = ('-----step1:设置max_borrow_memory=2147483647KB、'
                '2048GB2147483648KB、-128MB、2049GB、128KB;expect:合理报错-----')
        self.log.info(text)
        for value in self.invalid_values:
            res = self.pri_db_sh.execute_gsguc(
              'set', self.constant.GSGUC_SUCCESS_MSG,
                f"{self.param_name}='{value}'")
            self.log.info(res)
            res = self.pri_db_sh.restart_db_cluster(get_detail=True)
            self.log.info(res)
            msg = 'max_borrow_memory must be a integer multiple of 128MB'
            self.assertIn(msg, res, '执行失败：' + text)

    def tearDown(self):
        text = '-----step2:清理环境; expect:成功-----'
        self.log.info(text)
        res = self.pri_db_sh.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            f"{self.param_name}='{self.default_value}'")
        self.log.info(res)
        res = self.pri_db_sh.restart_db_cluster()
        self.log.info(res)
        status = self.pri_db_sh.get_db_cluster_status()
        self.assertTrue(res, '执行失败：' + text)
        self.assertTrue("Normal" or "Degrade" in status)
        res = self.common.show_param(self.param_name)
        self.log.info(res)
        self.assertEqual(self.default_value, res, '执行失败：' + text)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')